package yicr.untils;



import yicr.untils.common.NslCharset;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Description: csv util, the class has a bug which will appeared when the string has ",".
 * Created by E440 on 2017/4/30.
 *
 *
 */
public class NslUtilCsv {
    /**
     * 读取csv文件到List<String>数组，其中每一行为一个元素.
     * 对bom进行处理
     * @param file csv文件(路径+文件)
     * @return
     */
    public static List<String> readCsvFile(File file) throws IOException {
        List<String> dataList=new ArrayList<String>();
        try(BufferedReader br = new BufferedReader(new FileReader(file));) {

            String line = "";
            while ((line = br.readLine()) != null) {
                dataList.add(line);
            }
        }
        if(dataList.size()>0){
            String line1=dataList.get(0);
            NslEnumFileCharSet fileCharSet= NslUtilFile.detectEncoding(file);
            String newLine=NslUtilString.removeBomOfString(line1,fileCharSet);
            dataList.set(0,newLine);
        }
        return dataList;
    }

    public static List<String> readCsvFile(File file,String charSet) throws IOException {
        List<String> dataList=new ArrayList<String>();
        try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),charSet))) {

            String line = "";
            while ((line = br.readLine()) != null) {
                dataList.add(line);
            }
        }
        return dataList;
    }

    /**
     * 将dataList 导出到File文件,行分割符为 \r \n
     *
     * @param file csv文件(路径+文件名)，csv文件不存在会自动创建
     * @param dataList 数据
     * @return
     */
    public static boolean writeCsvFile(File file, List<String> dataList,String charset)  {
        boolean isSucess=false;
        try(FileOutputStream out=new FileOutputStream(file);
            OutputStreamWriter osw=new OutputStreamWriter(out);
            BufferedWriter bw =new BufferedWriter(osw,50*1024*1024)){
            if(dataList!=null && !dataList.isEmpty()){
                for(String data : dataList){
                    data= NslCharset.changeCharset(data,charset);
                    bw.append(data).append("\r").append("\n");
                }
            }
            isSucess=true;
        }catch (Exception e){
            isSucess=false;
        }
        return isSucess;
    }

    public static boolean writeCsvFile(File file, List<String> dataList){
        return writeCsvFile(file,dataList, NslCharset.UTF_8);
    }

}

